from socket import *
import threading  as td
import os,sys,pickle,urllib2,time,signal
import subprocess as sub

class CmdTimer(td.Thread):
	def __init__(self, cmd, timeout):
        	td.Thread.__init__(self)
        	self.cmd = cmd
        	self.timeout = timeout

	def run(self):
		self.p = sub.Popen(self.cmd)
        	self.p.wait()

    	def exec_cmd(self):
        	self.start()
        	self.join(self.timeout)
        	if self.isAlive():
            		#self.p.terminate()
			os.kill(self.p.pid, signal.SIGKILL)
            		self.join()



def open_port(ip,*port):
    target_ip = ip
    open_ports=[]
    for i in port:
        s = socket(AF_INET, SOCK_STREAM)
        s.settimeout(2)
        result = s.connect_ex((target_ip, i))
        if(result == 0):
            open_ports.append(i)
        try:
            s.close()
        except:
            pass
    return open_ports


def get_pic(ip):
	res=open_port(ip,80)
	if 80 in res:
		url="http://"+ip
		#os.popen("SCREENSHOOT/wkhtmltoimage-i386 --use-xserver --height 768 --width 1024 "+url+" PICS/"+ip+".png")
		cmd=["SCREENSHOOT/wkhtmltoimage-i386","--use-xserver","--height","768","--width","1024",url,"PICS/"+ip+".png"]
		CmdTimer(cmd, 30).exec_cmd()
	else:
		pass

def shot(fin):
	flog="screenshot.log"
	os.popen("mkdir PICS")
	os.popen("Xvfb :1 -screen 0 1024x768x24&")
	#os.popen("export DISPLAY=localhost:1.0")
	os.putenv("DISPLAY","localhost:1.0")
	for line in open(fin,"r"):
		ip=line.strip("\n")
		get_pic(ip)
		f=open(flog,"a")
		f.write(ip+"\n")
		f.close()

if __name__ == '__main__':
	fin=sys.argv[1]
	shot(fin)

